package cn.xlbweb.cli.service.impl;

import cn.xlbweb.cli.common.CommonProperties;
import cn.xlbweb.cli.dao.UserRepository;
import cn.xlbweb.cli.pojo.dto.UserInsertDTO;
import cn.xlbweb.cli.pojo.dto.UserListDTO;
import cn.xlbweb.cli.pojo.dto.UserUpdateDTO;
import cn.xlbweb.cli.pojo.jdo.UserDO;
import cn.xlbweb.cli.service.UserService;
import cn.xlbweb.cli.util.CliUtils;
import cn.xlbweb.ji.JwtUtils;
import cn.xlbweb.util.ConvertUtils;
import cn.xlbweb.util.ServletUtils;
import cn.xlbweb.util.res.ResponseServer;
import cn.xlbweb.util.res.ResponseTable;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.*;

/**
 * @author: bobi
 * @date: 2019-02-11 16:02
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private CommonProperties commonProperties;

    @Override
    public ResponseServer getCurrentUser() {
        String token = ServletUtils.getCurrentRequest().getHeader(commonProperties.getTokenName());
        String username = JwtUtils.getUsername(token);
        Map<String, Object> result = userRepository.getCurrentUser(username);
        return ResponseServer.success("当前登陆用户查询成功", result);
    }

    @Override
    public ResponseServer getUser(Integer id) {
        Map<String, Object> result = userRepository.getUserById(id);
        if (CollectionUtils.isEmpty(result)) {
            return ResponseServer.error("用户不存在");
        }
        return ResponseServer.success("查询成功", result);
    }

    @Override
    public ResponseTable listUser(UserListDTO dto) {
        PageRequest pageRequest = PageRequest.of(dto.getPage() - 1, dto.getSize(), Sort.Direction.DESC, "create_time");
        Page<Map<String, Object>> page = userRepository.listUser(dto.getUsername(), dto.getNickname(), pageRequest);
        return ResponseTable.success("查询成功", page.getTotalElements(), page.getContent());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer insertUser(UserInsertDTO dto) {
        UserDO checkUser = userRepository.findByUsername(dto.getUsername());
        if (Objects.nonNull(checkUser)) {
            return ResponseServer.error("账号已存在");
        }
        int count = userRepository.insertUser(dto);
        if (count > 0) {
            return ResponseServer.success("用户添加成功");
        }
        return ResponseServer.error("用户添加失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer updateUser(UserUpdateDTO dto) {
        int count = userRepository.updateUser(dto);
        if (count > 0) {
            return ResponseServer.success("用户更新成功");
        }
        return ResponseServer.error("用户更新失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer deleteUser(String ids) {
        int count = userRepository.deleteUser(ConvertUtils.strToIntegerList(ids));
        if (count > 0) {
            return ResponseServer.success("用户删除成功");
        }
        return ResponseServer.success("用户删除成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer resetPwd(String ids) {
        List<Integer> idList = ConvertUtils.strToIntegerList(ids);
        for (Integer id : idList) {
            // 生成随机密码
            String newPwd = RandomStringUtils.randomAlphanumeric(10);
            // 更新数据库
            UserDO dbUser = userRepository.getOne(id);
            dbUser.setPassword(DigestUtils.md5DigestAsHex(newPwd.getBytes()));
            userRepository.save(dbUser);
            // 发送邮件
            javaMailSender.send(CliUtils.buildResetPwd(dbUser.getMail(), newPwd));
        }
        return ResponseServer.success("用户密码重置成功");
    }
}
